//
//  DataStream.m
//  SimulacraDB
//
//  Created by Andre Cohen on 8/9/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "DataStream.h"
#include <stdio.h>
#include <sys/stat.h>

@implementation DataStream

-(id)initWithFilename:(NSString *)filename {
	FILE *f;
	if([self existsFile:filename])
		f = fopen([filename UTF8String],"r+");
	else
		f = fopen([filename UTF8String],"w+");
	
	handle = [[[NSFileHandle alloc] initWithFileDescriptor:f->_file] autorelease];
	
	return self;
}

-(void)finalize {
	[handle closeFile];
	[super finalize];
}

-(ByteArray *)readFrom:(int)loc length:(int)len {
	[handle seekToFileOffset:loc];
	NSData *data = [handle readDataOfLength:len];
	return [[[ByteArray alloc] initWithNSData:data] autorelease];
}

-(int)write:(ByteArray *)data at:(int)loc {
		[handle seekToFileOffset:loc];
	[handle writeData:[data toNSData]];
	return loc;
}

- (void)flush {
	[handle synchronizeFile];
}

-(BOOL)existsFile:(NSString *)filename {
	FILE *f = fopen([filename UTF8String], "r");
	if(f){
		fclose(f);
		return YES;
	}
	return NO;
}

- (int)fileSize {
	struct stat info;
	fstat([handle fileDescriptor],&info);
	return info.st_size;
}

@end
